package com.laf.common.utils.qrCode;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;

/**
 * 生成二维码，存储到阿里云oss，将url返回并且存储到数据库中
 */
@Slf4j
@Component
public class MyQrCodeUtil {

    @Autowired
    private QrConfig qrConfig;

    private final String PREFIX = "data:image/png;base64,";


    public String createQrCode(String json) {
        // 根据用户信息生成二维码
        byte[] bytes = QrCodeUtil.generatePng(json, qrConfig);
        return PREFIX+Base64.getEncoder().encodeToString(bytes);
    }

    // 将图片的url解析成json
    public String parseQrCode(String url) {
        // 将图片的ulr 转换为 Image 对象
        BufferedImage image = null;
        try {
            image = ImageIO.read(new URL(url));
            String decode = QrCodeUtil.decode(image);
            return decode;
        } catch (IOException e) {
            log.error("图片解析失败");
        }
        return null;
    }

    // 将图片的文件解析成json
    public String parseQrCode(MultipartFile file) {
        // 将图片的ulr 转换为 Image 对象
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String decode = QrCodeUtil.decode(inputStream);
            return decode;
        } catch (IOException e) {
            throw new RuntimeException("读取文件失败");
        }
    }


}
